package com.sy.controller;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.sy.dto.MemberDto;
import com.sy.entity.Member;
import com.sy.exception.BusinessException;
import com.sy.service.MemberService;
import com.sy.utils.FTPUtils;
import com.sy.utils.UuidUtils;
import com.sy.vo.MemberVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.*;

import static com.sy.constant.BusinessConstant.*;

/**
 * description: MemberController <br>
 * date: 2022/6/25 8:46 PM <br>
 * author: zoumaoji <br>
 * version: 1.0 <br>
 */
@RestController
@RequestMapping("member")
public class MemberController {
    @Autowired
    private MemberService memberService;

    @RequestMapping("all")
    public List<Member> getAllMembers() {
        List<Member> allMembers = memberService.getAllMembers();
        return allMembers;
    }

    @RequestMapping("get")
    public MemberDto getMemberById(Integer id) {
        MemberDto member = memberService.getMemberById(id);
        return member;
    }

    @RequestMapping("login")
    public MemberDto loginMember(HttpServletRequest request, MemberVo memberVo) {
        String attribute = (String) request.getSession().getAttribute(SESSION_VALIDATE_CODE);
        System.out.println(attribute);
        MemberDto member = memberService.login(memberVo,attribute);
        request.getSession().setAttribute("member", member);
        return member;
    }

    @RequestMapping("getMember")
    public Object getLoginMember(HttpServletRequest request) {
        Object member = request.getSession().getAttribute("member");
        System.out.println(member);
        if (Objects.isNull(member)) {
           throw new BusinessException(HttpStatus.BAD_REQUEST,"用户未登陆");
        }
        return member ;
    }

    @RequestMapping("register")
    public Boolean register(MemberVo memberVo) {
        Boolean aBoolean = memberService.registerMember(memberVo);
        return aBoolean;
    }


    @RequestMapping("update")
    public Boolean updateMember(Integer userId, String userName, String photo, String payPassword, Integer sexId, Date birth) {
        Member member = new Member();
        member.setId(userId);
        member.setUserName(userName);
        member.setPhoto(photo);
        member.setPayPassword(payPassword);
        member.setSexId(sexId);
        member.setBirth(birth);
        Boolean aBoolean = memberService.updateMember(member);
        return aBoolean;
    }

    //测试上传
    @RequestMapping("upload")
    public Map<String, Object> upload(MultipartFile file) {
        Map<String, Object> result = new LinkedHashMap<>();
        try {
            if (Objects.isNull(file)) {
                throw new BusinessException(HttpStatus.MULTI_STATUS, "当前未选中任何文件");
            }
            System.out.println("原始文件名:" + file.getOriginalFilename());
            //字节为单位，可以用于上传操作中限制文件大小
            System.out.println("文件大小:" + file.getSize());
            //在指定的目录中保存文件
            //(1)为了防止文件名发生重复，覆盖的问题，为上传的文件生成一个新的UUID作为文件名
            String newFileName = UuidUtils.generateUuid();
            //(2)文件的后缀依然使用原来的后缀
            String extName = FilenameUtils.getExtension(file.getOriginalFilename());
            //(3)得到一个新的文件名
            String newFullFileName = newFileName + "." + extName;
            //上传后的图片路径
            String newFullFilePath = DEFAULT_PICTURE_PATH + newFullFileName;
            //远程上传
            FTPUtils ftpUtils = new FTPUtils();
            Session session = ftpUtils.getSession(SFTP_REQ_HOST, SFTP_DEFAULT_PORT, SFTP_REQ_USERNAME, SFTP_REQ_PASSWORD);
            Channel channel = ftpUtils.getChannel(session);
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.cd("/www/server/tomcat/webapps/image");
            //(4)上传
            try (InputStream is = file.getInputStream()) {
                sftp.put(is, newFullFileName);
                result.put("success", true);

                result.put("data", newFullFilePath);
            } finally {
                ftpUtils.closeAll(sftp, channel, session);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("errMsg", e.getMessage());
        }
        return result;
    }


}
